package top.cwk.dubbo.web.controller.customer;

import java.util.ArrayList;
import java.util.List;
import java.util.LongSummaryStatistics;
import java.util.concurrent.*;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;
import top.cwk.dubbo.api.customer.ICustomerService;
import top.cwk.dubbo.api.hello.IHelloService;
import top.cwk.dubbo.entity.customer.Customer;

@Controller
@RequestMapping("/customer")
public class CustomerController {

	@Autowired
	private ICustomerService customerService;
	@Autowired
	private IHelloService helloService;

	private Logger logger = LoggerFactory.getLogger(this.getClass());


	@RequestMapping("saves")
	@ResponseBody
	public Customer customerList(Customer customer){
		Customer customer1 = helloService.saveCustomer(customer);
		System.out.println(customer1.toString());
		return customer1;
	}


	@RequestMapping("list")
	public String customerList(HttpServletRequest request){
		List<Customer> list = customerService.getAllCustomer();
		System.out.println(list.toString());
		request.setAttribute("customerList", list);
		return "customer/list";
	}
	
	@RequestMapping("update/{customerid}")
	public String updateCustomer(@PathVariable Integer customerid , HttpServletRequest request){
		request.setAttribute("customerInfo", customerService.getCustomerById(customerid));
		return "customer/update";
	}
	
	@RequestMapping("add")
	public String addCustomer(){
		return "customer/add";
	}
	
	@RequestMapping("save")
	public String saveCustomer(Customer customer){
		if(customer!=null){
			customerService.saveCustomer(customer);
		}
		return "redirect:/customer/list";
	}

	@RequestMapping("insert/{taskCount}")
	public String saveManyCustomer(@PathVariable Integer taskCount , HttpServletRequest request) throws InterruptedException {
		//设置核心池大小
		int corePoolSize = 5;

		//设置线程池最大能接受多少线程
		int maximumPoolSize = 20;

		//当前线程数大于corePoolSize、小于maximumPoolSize时，超出corePoolSize的线程数的生命周期
		long keepActiveTime = 200;

		//设置时间单位，秒
		TimeUnit timeUnit = TimeUnit.SECONDS;

		//设置线程池缓存队列的排队策略为FIFO，并且指定缓存队列大小为5
		BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(5);

		//创建ThreadPoolExecutor线程池对象，并初始化该对象的各种参数
		ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepActiveTime, timeUnit,workQueue);

		CountDownLatch countDownLatch = new CountDownLatch(taskCount);
		long start = System.currentTimeMillis();
		List<Future<Long>> countResult = new ArrayList<>();
		for (int i = 0 ; i<taskCount ; i++){
			CustomerThreadTask task = new CustomerThreadTask(customerService , countDownLatch , "thread"+i);
			Future<Long> run = executor.submit(task);
			countResult.add(run);
		}
		LongSummaryStatistics countMs = null;
		//等待所有线程结束
		countDownLatch.await(15, TimeUnit.HOURS);
		//执行其他操作
		countMs = countResult.stream().mapToLong((x) -> {
			try {
				return x.get();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
			return 0;
		}).summaryStatistics();
		//关闭线程池
		executor.shutdown();
		//统计结果
		long end = System.currentTimeMillis();

		String result = "创建线程数："+taskCount+",插入数据:"+taskCount*1000+"条，总线程执行时间："+countMs.getSum()+"ms，实际执行时间："+(end-start)+"ms";
		logger.info(result);
		request.setAttribute("result" , result);
		return "customer/result";
	}

}
